package com.kerbores.nutz.ioc;

import java.io.StringReader;

import org.nutz.ioc.IocLoading;
import org.nutz.ioc.ObjectLoadException;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.json.JsonLoader;
import org.nutz.ioc.meta.IocObject;
import org.nutz.json.Json;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import com.kerbores.utils.net.UrlPoster;

/**
 * 设计目标,配置化加载,环境感知
 * 
 * 
 * @author 王贵源
 * @email kerbores@kerbores.com
 *
 *        create at 2015年10月12日 下午6:00:34
 */
public class KerboresProjectLoader extends JsonLoader {

	protected JsonLoader proxy;
	private static final Log log = Logs.get();

	/**
	 * @param proxy
	 */
	public KerboresProjectLoader(String[] args) {
		super(new String[0]);
		String confPath = (args.length > 0) ? args[0] : "ioc.properties";
		String env = System.getenv("env_type");// 获取环境
		PropertiesProxy config = new PropertiesProxy(false, confPath);
		String loadingUrl = null;
		if (Strings.isBlank(env)) {// 未设置即为线下开发环境
			loadingUrl = config.get("offline.url");
			log.debug("kerbores Ioc loading as offline from url " + loadingUrl + " \n");
		} else {// 线上加载
			loadingUrl = config.get("online.url");
			log.debug("kerbores Ioc loading as online from url " + loadingUrl + "  \n");
		}
		NutMap data = NutMap.NEW();
		String loadingInfo = UrlPoster.simpleUTF8Post(loadingUrl, data);// 请求数据
		String json = Json.toJson(Json.fromJson(loadingInfo));
		log.debug("kerbores Ioc Define as:\n" + json);// 打印日志
		this.proxy = new JsonLoader(new StringReader(json));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.nutz.ioc.IocLoader#getName()
	 */
	@Override
	public String[] getName() {
		return this.proxy.getName();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.nutz.ioc.IocLoader#load(org.nutz.ioc.IocLoading,
	 * java.lang.String)
	 */
	@Override
	public IocObject load(IocLoading loading, String name) throws ObjectLoadException {
		return this.proxy.load(loading, name);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.nutz.ioc.IocLoader#has(java.lang.String)
	 */
	@Override
	public boolean has(String name) {
		return this.proxy.has(name);
	}

}
